#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import cgi
import datetime
import wsgiref.handlers

from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
import facebook
from facebook import FacebookError
from db_wish import Wish,FBUser
import random
#from guestbook import *
version='beta 1.0'
g_args={
  'uid':'',
  'address':'118.169.28.155',    
  'DoEditProfile=1':0
        }
g_notification_word=''
#g_ADDRESS='wolkefacebook.appspot.com'
FACEBOOK_API_KEY ='ea45225dd415778778219a81c0a6e810'
FACEBOOK_SECRET_KEY ='418ef72221e0d17e77d935f4a5246335'


class SaveMyWish(webapp.RequestHandler):
    def post(self):
        fb = facebook.Facebook(FACEBOOK_API_KEY, FACEBOOK_SECRET_KEY)
        if fb.check_session(self.request) and fb.added:
            pass
        else:
            url = fb.get_add_url()
            self.response.out.write('<script language="javascript">top.location.href="' + url + '"</script>')
            return
        #save data
        r_uid = self.request.get('uid')
        r_word = self.request.get('word')
        r_year = self.request.get('year')
        
        #find user then save wish obj
        u = FBUser(uid=r_uid,
                 key_name=r_uid)
        u.put()
        
            #u=User.get_by_key_name(r_uid)
        w=Wish(user=u,
               word=r_word,
               year=int(r_year))
        w.put()
        
        #Set Status        
        try:
            fb.status.set(r_word)
           
        except:
            self.response.out.write('error')
            return

        #notification
        al=int(fb.admin.getAllocation('notifications_per_day'))
        friend = fb.friends.get()
        uids = fb.users.getInfo(friend,['uid'])
        to_ids=[]
        #set to_ids
        i=0
        i_max=int(len(uids))
        if i_max > (i+al):
            i_max=(i+al)
        while i < i_max:
            to_ids.append(uids[i]['uid'])
            i=i+1

            #fb.notifications.send(to_ids,g_notification_word,'user_to_user')
        #JSON data           
        self.response.out.write('{"done":'+u.uid+'}');
        
class GetWishList(webapp.RequestHandler):
    def post(self):
        parm = self.request.get('parm')
        page = self.request.get('page')#page index
         
        fb = facebook.Facebook(FACEBOOK_API_KEY, FACEBOOK_SECRET_KEY)
        if fb.check_session(self.request) and fb.added:
            pass
        else:
            url = fb.get_add_url()
            self.response.out.write('<script language="javascript">top.location.href="' + url + '"</script>')
            return
        # use fids to search firned wish
        users = db.GqlQuery("SELECT * "
                            "FROM FBUser ")
        fids=[]
        words=[]
        created=[]
        years=[]
        for user in users:            
            fids.append(str(user.uid))
            i=0
            s=''
            for w in user.wishs:
               i=int(i)+1
            index = random.randint(0, i-1)
            words.append(user.wishs[index].word)
            created.append(user.wishs[index].created)
            years.append(user.wishs[index].year)
            
            
        uIs =fb.users.getInfo(fids,['name','pic_square'])#userInfos
        
       
        self.response.out.write('[')
        for i in range(len(uIs)):
            self.response.out.write(u'{"name":"%s","pic_square":"%s","word":"%s","created":"%s","year":"%s"' %
                                   (                                     
                                     uIs[i]['name'],
                                     uIs[i]['pic_square'],
                                     #'#',
                                     words[i],
                                     created[i],
                                     years[i])
                                    )
            if i==(len(uIs)-1):
                self.response.out.write('}');
            else:
                self.response.out.write('},');
        self.response.out.write(']')

        return
        #if parm = friends then
        fids=fb.friends.get()
        # use fids to search firned wish
        
        uIs =fb.users.getInfo(fids,['name','pic_square'])#userInfos
        # I don`t know why /i can not save data , I would fix this problem later 2009.1204    
        #query =Wish.all()
        #wishs = query.fetch(1,1)
        #wishs = db.GqlQuery("SELECT * "
        #                    "FROM Wish "
        #                    "ORDER BY created DESC LIMIT 10")
        #self.response.out.write(wishs)
       
        self.response.out.write('[')
        for i in range(len(uIs)):
            self.response.out.write(u'{"name":"%s","pic_square":"%s","word":"%s","created":"%s"' %
                                   (                                     
                                     uIs[i]['name'],
                                     #uIs[i]['pic_square'],
                                     '#',
                                     "haha",
                                     "2009.1212")
                                    )
            if i==(len(uIs)-1):
                self.response.out.write('}');
            else:
                self.response.out.write('},');
        self.response.out.write(']')
        
class MainPage(webapp.RequestHandler):
  def get(self):
     self.response.out.write('WOO')

     
  def post(self):
     fb = facebook.Facebook(FACEBOOK_API_KEY, FACEBOOK_SECRET_KEY)
     
     if fb.check_session(self.request) and fb.added:
        
        pass
     else:
        url = fb.get_add_url()
        self.response.out.write('<script language="javascript">top.location.href="' + url + '"</script>')
        return
     #set parm
     g_args['uid']=fb.uid
  #wrtie teplate
      
     self.response.out.write(template.render('index.html',{'args':g_args}))

class CheckData(webapp.RequestHandler):
    def get(self):
        self.response.out.write('<html><body>')

        greetings = db.GqlQuery("SELECT * "
                                "FROM Wish ")

        for greeting in greetings:

          self.response.out.write('%s wrote:' % greeting.user.uid)
          self.response.out.write('<blockquote>%s</blockquote> time:%s<br />' %
                                   (
                                      cgi.escape(greeting.word),
                                      greeting.created
                                    )

                                  )
        self.response.out.write("=================<br />")

        
        users = db.GqlQuery("SELECT * "
                                "FROM FBUser ")
        
        for user in users:
            self.response.out.write('<h3>%s</h3> wrote:<br/>' % user.uid)
            self.response.out.write('<ui>')
            for wish in user.wishs:
                self.response.out.write('<li>%s - %s/%s</li>' % (wish.year,wish.word,wish.created))
            self.response.out.write('</ui>')
        
        self.response.out.write("""
              <form action="/sign" method="post">
                <div><input type="text" name="uid" value="uid" /></div>
                <div><textarea name="word" rows="3" cols="60"></textarea></div>
                <div><input type="submit" value="Sign Guestbook"></div>
              </form>
            </body>
          </html>""")
        
class Clear(webapp.RequestHandler):
    def get(self):        
        db.delete(FBUser.all())
        db.delete(Wish.all())
        self.response.out.write("ok")

application = webapp.WSGIApplication([
  ('/', MainPage),
  ('/SaveMyWish.api',SaveMyWish),
  ('/GetWishList.api',GetWishList),
  ('/CheckData.api',CheckData),
  ('/Clear',Clear)
], debug=True)


def main():
  wsgiref.handlers.CGIHandler().run(application)
  
if __name__ == '__main__':
  main()
